package com.xhh.nphm.web.controller.system;

import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.system.domain.BUserTelNo;
import com.xhh.nphm.system.mapper.CommonDao;
import com.xhh.nphm.system.service.BUserTelNoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/tno")
public class BUserTelNoController extends BaseController {
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private BUserTelNoService userTelNoService;

    /**
     * 随机获取未被占用的分机号
     * @return 分机号
     */
    @PostMapping("/getRandomTelNo")
    public String getRandomTelNo(){
        List<String> telNos = commonDao.fetchRandomTklTNo();
        return telNos.get(new Random().nextInt(telNos.size())) ;
    }

    /**
     * 更新分机号使用情况
     *
     * @param tno 分机号
     * @return 影响结果
     */
    @PostMapping("/updateTelStatus")
    public AjaxResult updateTelStatus(String tno){
        AjaxResult result = AjaxResult.success("未获取到该分机号");
        BUserTelNo userTelNo = userTelNoService.findOneByTelNo(tno);
        if (userTelNo != null) {
            switch (userTelNo.getUseState()) {
                case 0:
                    userTelNoService.updateTelState(userTelNo,getSysUser().getLoginName(),0);
                    result = AjaxResult.success("签入成功");
                    break;
                case 1:
                    userTelNoService.updateTelState(userTelNo,null,1);
                    result = AjaxResult.success("签出成功");
                    break;
                default:
                    break;
            }
        }
        return result;
    }


    /**
     * 获取分机号使用情况
     *
     * @param tno 分机号
     * @return 影响结果
     */
    @PostMapping("/chkTelNoStatus")
    public int chkTelNoStatus(String tno){
        BUserTelNo userTelNo = userTelNoService.findOneByTelNo(tno);
        return userTelNo.getUseState() == 1 && !getLoginName().equals(userTelNo.getLoginName()) ? 1 : 0;
    }


}
